package main;

import gui.TerminalPanel;

import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MainWindow extends JFrame implements Runnable {
	private static final long serialVersionUID = 2427719776404652569L;

	public static MainWindow instance = null;
	private JTabbedPane tabbedPane;
	int terminalCount = 0;
	
	public MainWindow()
	{
		super();
		
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {} 
		catch (InstantiationException e) {} 
		catch (IllegalAccessException e) {} 
		catch (UnsupportedLookAndFeelException e) {}
		
		tabbedPane = new JTabbedPane();
		//tabbedPane.setForeground(Color.BLACK);
		//tabbedPane.setBackground(Color.BLACK);
		add(tabbedPane);
		
		this.setBackground(Color.BLACK);
		this.setForeground(Color.BLACK);
		this.setSize(640, 480);
		this.setTitle("GeoTerminal v0.3");
		this.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		instance = this;
		
		Thread thread = new Thread(this);
		thread.start();
	}
	
	synchronized public void addTerminal(TerminalPanel term)
	{
		terminalCount++;
		tabbedPane.addTab("Terminal #" + terminalCount, term);
		term.tabTitle = "Terminal #" + terminalCount;
		term.index = terminalCount;
	}
	
	synchronized public void removeTerminal(TerminalPanel term)
	{
		try
		{
			tabbedPane.removeTabAt(tabbedPane.indexOfTab(term.tabTitle));
		}
		catch(Exception e) { }
	}
	
	synchronized public void setTabTitle(TerminalPanel term, String title)
	{
		tabbedPane.setTitleAt(tabbedPane.indexOfTab(term.tabTitle), title);
		term.tabTitle = title;
	}
	
	public static void main(String[] args) {
		new MainWindow();
	}

	@Override
	public void run() {
		int port = 4444;
		
		try {
			Scanner s = new Scanner(new File("geoport.txt"));
			port = s.nextInt();
			s.close();
		} catch (FileNotFoundException e1) { port = 4444; }
		
		try {
			ServerSocket socket = new ServerSocket(port);
			
			while(true)
			{
				Socket csock = socket.accept();
				new Client(csock);
			}
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, "Already running!");
			System.exit(1);
		}
	}

}
